package com.streetsmart.main;

/**
 * User can enter details on a event
 */
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONException;

import com.streetsmart.DBManager;
import com.streetsmart.MyEvent;
import com.streetsmart.MyLocation;
import com.streetsmart.R;
import com.streetsmart.Utilities;
import com.streetsmart.MySuggestionsAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * 
 * @author bhavani sudha
 * 
 */
public class SSReportTaskActivity extends Activity implements
		OnItemSelectedListener, OnCheckedChangeListener, OnClickListener {

	DBManager dbHelper;
	EditText name;
	Spinner category;
	RadioGroup where;
	RadioButton custom;
	RadioButton autoPick;
	RadioButton radioSpecific;
	TextView textViewWhere;
	RadioGroup when;
	Button startDatePick;
	Button endDatePick;
	Button startTimePick;
	Button endTimePick;
	Button delete;
	Context context = this;
	String eventName = "custom";
	String eventCategory = "restaurant";
	String eventLocation = "";
	String eventType = "Must";
	String startDate;
	String startTime;
	String endDate;
	String endTime;
	final String autopickMsg = "Will be auto suggested later";
	String locationMsg = "";
	int year;
	int month;
	int day;
	int hour;
	int minutes;
	int seconds;
	View view;
	MyEvent event;
	MyLocation location;
	Date startingTime;
	Date endingTime;

	private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker v, int yr, int monthOfYear,
				int dayOfMonth) {
			year = yr;
			month = monthOfYear;
			day = dayOfMonth;
			try {
				updateDateDisplay(view);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (view.getId() == R.id.ButtonStartDatePicker) {
				startTimePick.setEnabled(true);
			} else {
				endTimePick.setEnabled(true);
			}
		}
	};

	private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker v, int hourOfDay, int minute) {
			hour = hourOfDay;
			minutes = minute;
			updateTimeDisplay(view);
		}
	};

	// String mrepeat;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.ssreport_task);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.sswindow_title);
		dbHelper = new DBManager(context);
		delete = (Button) findViewById(R.id.ButtonDelete);
		delete.setVisibility(View.GONE);
		name = (EditText) findViewById(R.id.editTextName);
		category = (Spinner) findViewById(R.id.spinnerCategory);
		where = (RadioGroup) findViewById(R.id.radioGroupLocation);
		when = (RadioGroup) findViewById(R.id.radioGroupTimeType);
		startDatePick = (Button) findViewById(R.id.ButtonStartDatePicker);
		endDatePick = (Button) findViewById(R.id.ButtonEndDatePicker);
		startTimePick = (Button) findViewById(R.id.ButtonStartTimePicker);
		endTimePick = (Button) findViewById(R.id.ButtonEndTimePicker);
		custom = (RadioButton) findViewById(R.id.radioCustom);
		autoPick = (RadioButton) findViewById(R.id.radioAutoPick);
		radioSpecific = (RadioButton) findViewById(R.id.radioSpecific);
		textViewWhere = (TextView) findViewById(R.id.TextViewWhere);
		category.setOnItemSelectedListener(this);
		category.setSelected(true);
		ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter
				.createFromResource(context, R.array.categories,
						android.R.layout.simple_spinner_item);
		arrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		category.setAdapter(arrayAdapter);
		where.setOnCheckedChangeListener(this);
		when.setOnCheckedChangeListener(this);
		startDatePick.setOnClickListener(this);
		endDatePick.setOnClickListener(this);
		startTimePick.setOnClickListener(this);
		endTimePick.setOnClickListener(this);
		radioSpecific.setChecked(true);
		autoPick.setChecked(true);
		//updateAddressView(autopickMsg, 0);
		updateAddressView(autopickMsg);
		// mtextViewWhere.setText(autopickMsg); // does the same thing as
		// previous line
		name.requestFocus();
		updateCurrentTimeDisplay();
	}

	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		eventCategory = arg0.getItemAtPosition(arg2).toString();
		if (eventCategory.equals("other")) {
			custom.setChecked(true);
			autoPick.setEnabled(false);
		} else {
			autoPick.setEnabled(true);
			autoPick.setChecked(true);
		}
	}

	public void updateAddressView(String address){
		textViewWhere.setText(address);
	}
	
	public void updateAddressView(String address, int color) {
		if (color == 0) {
			textViewWhere.setTextColor(android.R.color.darker_gray);
		} else {
			textViewWhere.setTextColor(Color.RED);
		}
		textViewWhere.setText(address);
		
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		eventCategory = arg0.getItemAtPosition(0).toString();
	}

	public void onCheckedChanged(RadioGroup group, int checkedId) {

		// TODO need to write a code for autocompletion of the address.
		// TODO store the address in a separate table to facilitate
		// autocompletion
		if (group.getId() == R.id.radioGroupLocation) {
			int id = group.getCheckedRadioButtonId();
			MySuggestionsAdapter suggestionsList = null;
			switch (id) {
			case R.id.radioCustom:
				if (eventLocation.length() == 0
						|| eventLocation.equals("autopick")) {
					// if the user
					// wants to
					// specify the
					// location, pop
					// a dialog to
					// get the
					// address from
					// the user and
					// display below
					LayoutInflater layoutInteface = LayoutInflater
							.from(context);
					View prompts = layoutInteface.inflate(
							R.layout.ssget_address_dialog, null);
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							context);
					alertDialogBuilder.setView(prompts);
					final AutoCompleteTextView userInput = (AutoCompleteTextView) prompts
							.findViewById(R.id.editTextgetAddress);

					dbHelper.close();
					Cursor cur = dbHelper.getAllUserAddresses("");

					suggestionsList = new MySuggestionsAdapter(context, cur);
					userInput.setAdapter(suggestionsList);
					cur.close();
					dbHelper.close();
					alertDialogBuilder.setCancelable(false).setPositiveButton(
							"OK", new DialogInterface.OnClickListener() {
								boolean result = false;

								public void onClick(DialogInterface dialog,
										int which) {
									result = true;
									eventLocation = userInput.getText()
											.toString();
									textViewWhere = (TextView) findViewById(R.id.TextViewWhere);
									if (eventLocation != null
											& eventLocation.length() != 0) {
										try {
											if (!dbHelper
													.checkIfPresent(eventLocation)) {
												result = dbHelper
														.saveRecentUserAddress(eventLocation);
											}
											if (result) {
												ContentValues cv = dbHelper
														.getUserAddressDetails(eventLocation);
												location = new MyLocation(
														cv.getAsDouble("latitude"),
														cv.getAsDouble("longitude"),
														eventLocation);
												locationMsg = location
														.getAddress();
												updateAddressView(locationMsg);
												//updateAddressView(locationMsg,
														//0);
											} else {
												locationMsg = "Location not Found. Please try again!";
												updateAddressView(locationMsg);
												//updateAddressView(locationMsg,
														//1);
											}
										} catch (JSONException e) {
											locationMsg = "Location not Found. Please try again!";
											updateAddressView(locationMsg);
											//updateAddressView(locationMsg, 1);
											e.printStackTrace();
										}

									} else {
										location = null;
										locationMsg = "Location not Found. Please try again!";
										updateAddressView(locationMsg);
										//updateAddressView(locationMsg, 1);
									}
								}

							});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();

				}
				break;
			case R.id.radioAutoPick:
				eventLocation = "autopick";
				updateAddressView(autopickMsg);
				//updateAddressView(autopickMsg, 0);
				location = null;
				break;
			}
			if (suggestionsList != null) {
				suggestionsList.close();
			}
		} else if (group.getId() == R.id.radioGroupTimeType) {
			int id = group.getCheckedRadioButtonId();
			switch (id) {
			case R.id.radioSpecific:
				eventType = "Must";
				break;
			case R.id.radioInterval:
				eventType = "Good";
				break;
			}
		}
		// mtextViewWhere.setText("blabla");
	}

	public void getDate(View v) {
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		view = v;
		DatePickerDialog datePickerDialog = new DatePickerDialog(context,
				dateSetListener, year, month, day);
		datePickerDialog.show();
	}

	public void getTime(View v) {
		final Calendar c = Calendar.getInstance();
		hour = c.get(Calendar.HOUR_OF_DAY);
		minutes = c.get(Calendar.MINUTE);
		view = v;
		TimePickerDialog timePickerDialog = new TimePickerDialog(context,
				timeSetListener, hour, minutes, false);
		timePickerDialog.show();
	}

	public void updateDateDisplay(View v) throws ParseException {
		// Need to check for adding 0 to day as well to make it two in length.
		String temp = "" + month;
		String dateString = "/" + (day) + "/" + (year);
		if (("" + month).length() == 1) {
			temp = "0" + month;
		}
		//startDatePick.setTextColor(android.R.color.black);
		//endDatePick.setTextColor(android.R.color.black);
		if (v.getId() == R.id.ButtonStartDatePicker) {
			startDate = "" + (month + 1) + dateString;
			startDatePick.setText(startDate);
			// mStartDate = temp + dateString;
			startingTime = Utilities.getDate(startDate);
			if( startingTime.getTime() < Utilities.getTodaysTimeStamp()){
				//startDatePick.setTextColor(R.color.red);
				startDatePick.setText("Invalid. Try Again!");
			}
		} else if (v.getId() == R.id.ButtonEndDatePicker) {
			endDate = "" + (month + 1) + dateString;
			endDatePick.setText(endDate);
			// mEndDate = temp + dateString;
			endingTime = Utilities.getDate(endDate);
			Log.d("TIME_DIFF", "" + "end:" + endingTime.getTime() + " startingTiem:" + startingTime.getTime());
			if( endingTime.getTime() < Utilities.getTodaysTimeStamp()){
				//endDatePick.setTextColor(R.color.red);
				endDatePick.setText("Invalid. Try Again!");
			}
		}
	}

	public void updateTimeDisplay(View v) {
		if (v.getId() == R.id.ButtonStartTimePicker) {
			startTime = "" + hour + ":" + minutes;
			startTimePick.setText(startTime);
			startingTime.setHours(hour);
			startingTime.setMinutes(minutes);
		} else if (v.getId() == R.id.ButtonEndTimePicker) {
			endTime = "" + hour + ":" + minutes;
			endTimePick.setText(endTime);
			endingTime.setHours(hour);
			endingTime.setMinutes(minutes);
			if( endingTime.getTime() < startingTime.getTime()){
				endDatePick.setText("Invalid. Try Again!");
			}
		}
	}

	public void updateCurrentTimeDisplay() {
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		hour = c.get(Calendar.HOUR_OF_DAY);
		minutes = c.get(Calendar.MINUTE);
		try {
			updateDateDisplay(findViewById(R.id.ButtonStartDatePicker));
			updateDateDisplay(findViewById(R.id.ButtonEndDatePicker));
			updateTimeDisplay(findViewById(R.id.ButtonStartTimePicker));
			updateTimeDisplay(findViewById(R.id.ButtonEndTimePicker));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// collects all the user entered details about the event and records into
	// the database tables
	public void add(View v) {
		// TODO get all the fields into an event class and store it in database
		// Prompt user to enter name, date if he dint enter anything
		// calculate duration by the difference from start and end date for MUST
		// events.
		// For Good to do events assume 30 mins as duration by default
		// TODO After adding reset all fields so that the activity is ready for
		// new input
		eventName = name.getText().toString();
		/*
		 * AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
		 * builder.setTitle("Selection") .setMessage(" " + meventName + " " +
		 * meventCategory + " " + startTime.toString() + " " +
		 * endTime.toString() + " " + meventType + " ")
		 * .setCancelable(false).setPositiveButton("Ok", null);
		 * builder.create().show();
		 */
		event = new MyEvent(eventName, eventCategory, location, startingTime,
				endingTime, eventType);
		dbHelper.saveEvent(event);
		onBackPressed();
	}

	public void repeat(View v) {
		// TODO handle logic for repeat here.
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ButtonEndDatePicker:
			getDate(v);
			break;
		case R.id.ButtonStartDatePicker:
			getDate(v);
			break;
		case R.id.ButtonStartTimePicker:
			getTime(v);
			break;
		case R.id.ButtonEndTimePicker:
			getTime(v);
			break;
		}
	}

	public void onBackPressed() {
		dbHelper.close();
		finish();
	}

	public void onDestroy() {
		dbHelper.close();
		super.onDestroy();
	}

}
